<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 200px;" placeholder="请输入名字" />
      <el-button v-permission="['GET /admin/store/list']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button v-permission="['POST /admin/store/create']" class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
      <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>
      <el-table-column align="center" label="id" prop="id" sortable />
      <el-table-column align="center" label="名字" prop="name" sortable />
      <el-table-column align="center" label="人均消费" prop="avgConsumer" sortable />
      <el-table-column align="center" label="商家账号" prop="username" sortable />
      <!--      <el-table-column align="center" label="营业时间" prop="businessHours" sortable />-->
      <el-table-column align="center" label="订座电话" prop="dingzuoPhone" sortable />
      <!--      <el-table-column align="center" label="就餐人数" prop="jcCount" sortable />-->
      <!--      <el-table-column align="center" label="就餐日期(天内)" prop="jcDay" sortable />-->
      <el-table-column align="center" label="就餐起始时间" prop="jcBeginTime" sortable />
      <el-table-column align="center" label="就餐结束时间" prop="jcEndTime" sortable />
      <!--      <el-table-column align="center" label="就餐时间间隔" prop="jcTimeInterval" sortable />-->
      <!--      <el-table-column align="center" label="大厅数量" prop="jcPlaceHall" sortable />-->
      <!--      <el-table-column align="center" label="包间数量" prop="jcPlaceBigBag" sortable />-->

      <el-table-column align="center" label="操作" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-permission="['POST /admin/store/update']" type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button v-permission="['POST /admin/store/delete']" type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog width="90%" :fullscreen="true" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="100px" style="width: 90%; margin-left:50px;">
        <el-form-item label="名字" prop="name">
          <el-input v-model="dataForm.name" />
        </el-form-item>
        <el-form-item label="商户账号" prop="username">
          <el-input v-model="dataForm.username" />
        </el-form-item>
        <el-form-item label="排序时间" prop="sortTime">
          <el-date-picker
            v-model="dataForm.sortTime"
            type="datetime"
            placeholder="选择排序时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            align="right"
            :picker-options="pickerOptions"
            @change="getSortTime"
          />
        </el-form-item>
        <el-form-item v-permission="['POST /admin/store/create']" label="推荐指数" prop="name">
          <el-rate v-model="dataForm.recommendIndex" />
        </el-form-item>
        <el-form-item v-permission="['POST /admin/store/create']" label="是否推荐" prop="name">
          <el-radio v-model="dataForm.isRecommended" :label="true">推荐</el-radio>
          <el-radio v-model="dataForm.isRecommended" :label="false">不推荐</el-radio>
        </el-form-item>
        <el-form-item label="热榜说明">
          <el-input v-model="dataForm.shortDescription" />
        </el-form-item>
        <el-form-item label="经纬度" prop="latLon">
          <el-input v-model="dataForm.latLon" /><a href="https://lbs.qq.com/getPoint/#Y" style="color: red;" target="_blank">坐标助手</a>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="dataForm.address" />
        </el-form-item>
        <el-form-item label="商户背景图">
          <el-upload
            :action="uploadPath"
            :show-file-list="false"
            :headers="headers"
            :on-success="uploadBackPicUrl"
            class="avatar-uploader"
            accept=".jpg,.jpeg,.png,.gif"
          >
            <img v-if="dataForm.backPicUrl" :src="dataForm.backPicUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="商户标题图">
          <el-upload
            :action="uploadPath"
            :show-file-list="false"
            :headers="headers"
            :on-success="uploadPicUrl"
            class="avatar-uploader"
            accept=".jpg,.jpeg,.png,.gif"
          >
            <img v-if="dataForm.picUrl" :src="dataForm.picUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="图片列表" prop="images">
          <el-upload
            :action="uploadPath"
            :limit="5"
            :headers="headers"
            :file-list="galleryFileList"
            :on-exceed="uploadOverrun"
            :on-success="handleGalleryUrl"
            :on-remove="handleRemove"
            multiple
            accept=".jpg,.jpeg,.png,.gif"
            list-type="picture-card"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>
        <el-form-item label="人均消费" prop="avgConsumer">
          <el-input v-model.number="dataForm.avgConsumer" />
        </el-form-item>
        <!--        <el-form-item label="营业时间" prop="businessHours">-->
        <!--          <el-input v-model="dataForm.businessHours" />-->
        <!--        </el-form-item>-->
        <el-form-item label="订座电话" prop="dingzuoPhone">
          <el-input v-model="dataForm.dingzuoPhone" />
        </el-form-item>
        <!--        <el-form-item label="就餐人数" prop="jcCount">-->
        <!--          <el-input v-model="dataForm.jcCount" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="就餐日期(天内)" prop="jcDay">-->
        <!--          <el-input v-model="dataForm.jcDay" />-->
        <!--        </el-form-item>-->
        <el-form-item label="就餐起始时间" prop="jcBeginTime">
          <el-time-select
            v-model="dataForm.jcBeginTime"
            :picker-options="{
              start: '08:00',
              step: '1:00',
              end: '12:00'
            }"
            placeholder="就餐起始时间"
          />
        </el-form-item>

        <el-form-item label="就餐结束时间" prop="jcEndTime">
          <el-time-select
            v-model="dataForm.jcEndTime"
            :picker-options="{
              start: '12:00',
              step: '1:00',
              end: '24:00'
            }"
            placeholder="就餐结束时间"
          />
        </el-form-item>
        <!--        <el-form-item label="就餐时间间隔" prop="jcTimeInterval">-->
        <!--          <el-input v-model.number="dataForm.jcTimeInterval" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="大厅数量" prop="jcPlaceHall">-->
        <!--          <el-input v-model.number="dataForm.jcPlaceHall" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="包间数量" prop="jcPlaceBigBag">-->
        <!--          <el-input v-model.number="dataForm.jcPlaceBigBag" />-->
        <!--        </el-form-item>-->
        <el-form-item v-for="c in tagCategoryList" :label="c.name">
          <el-checkbox v-for="t in c.tagList" :key="t.id" v-model="dataForm.tags" :value="t.id" :label="t.id">{{ t.name }}</el-checkbox>
        </el-form-item>

        <!--        </el-form-item>-->
        <el-form-item label="介绍">
          <editor v-model="dataForm.description" :init="editorInit" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
</style>

<script>
import { listStore, createStore, updateStore, deleteStore } from '@/api/store'
import { listTagCategoryList } from '@//api/tagcategory'
import { listTagsList } from '@//api/tag'
import { checkUsername } from '@//api/admin'
import { createStorage, uploadPath } from '@/api/storage'
import { getToken } from '@/utils/auth'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import Editor from '@tinymce/tinymce-vue'
export default {
  name: 'Store',
  components: { Pagination, Editor },
  data() {
    var validateLatLon = (rule, value, callback) => {
      const i = value.indexOf(',')

      if (value === '') {
        callback(new Error('经纬度不能为空'))
      } else if (i === -1) {
        callback(new Error('不是正确的经纬度格式，直接把坐标助手中的坐标拷贝过来!'))
      } else {
        callback()
      }
    }

    var validateUsername = (rule, value, callback) => {
      checkUsername({ username: value, storeId: this.dataForm.id })
        .then(({ data }) => {
          if (data.data) {
            callback()
          } else {
            callback(new Error('账号不可用!'))
          }
        })
    }
    return {
      uploadPath,
      list: [],
      total: 0,
      listLoading: true,
      galleryFileList: [],
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined,
        content: undefined,
        sort: 'add_time',
        order: 'desc'
      },
      dataForm: {
        name: '',
        username: '',
        sortTime: '',
        recommendIndex: 1,
        isRecommended: false,
        description: '',
        latLon: '',
        address: '',
        images: [],
        avgConsumer: '',
        businessHours: '',
        dingzuoPhone: '',
        jcCount: '',
        jcDay: '',
        jcBeginTime: '',
        jcEndTime: '',
        jcTimeInterval: '',
        jcPlaceHall: '',
        jcPlaceBigBag: '',
        tags: []

      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        name: [
          { required: true, message: '名字不能为空', trigger: 'blur' }
        ],
        sortTime: [
          { required: true, message: '排序时间不能为空', trigger: 'blur' }
        ],
        latLon: [
          { validator: validateLatLon, trigger: 'blur' }
        ],
        description: [
          { required: true, message: '介绍不能为空', trigger: 'blur' }
        ],
        username: [
          { validator: validateUsername, trigger: 'blur' }
        ],
        address: [
          { required: true, message: '地址不能为空', trigger: 'blur' }
        ],
        avgConsumer: [
          { required: true, message: '人均消费不能为空', trigger: 'blur' }
        ],
        businessHours: [
          { required: true, message: '营业时间不能为空', trigger: 'blur' }
        ],
        dingzuoPhone: [
          { required: true, message: '订座电话不能为空', trigger: 'blur' }
        ],
        jcCount: [
          { required: true, message: '就餐人数不能为空', trigger: 'blur' }
        ],
        jcDay: [
          { required: true, message: '就餐日期(天内)不能为空', trigger: 'blur' }
        ],
        jcBeginTime: [
          { required: true, message: '就餐起始时间不能为空', trigger: 'blur' }
        ],
        jcEndTime: [
          { required: true, message: '就餐结束时间不能为空', trigger: 'blur' }
        ],
        jcTimeInterval: [
          { required: true, message: '就餐时间间隔不能为空', trigger: 'blur' }
        ],
        jcPlaceHall: [
          { required: true, message: '大厅数量不能为空', trigger: 'blur' }
        ],
        jcPlaceBigBag: [
          { required: true, message: '包间数量不能为空', trigger: 'blur' }
        ]
      },
      downloadLoading: false,
      editorInit: {
        language: 'zh_CN',
        height: 500,
        convert_urls: false,
        plugins: ['advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'],
        toolbar: ['searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample', 'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'],
        images_upload_handler: function(blobInfo, success, failure) {
          const formData = new FormData()
          formData.append('file', blobInfo.blob())
          createStorage(formData).then(res => {
            success(res.data.data.url)
          }).catch(() => {
            failure('上传失败，请重新上传')
          })
        }
      },
      ycrangeList: ['早餐', '午餐', '下午茶', '晚餐', '夜宵'],
      mstypeList: ['自助餐', '快餐', '中餐', '西餐', '火锅', '甜点饮品', '烧烤烤肉'],
      mscaixiList: ['滇味', '川菜', '湘菜', '江浙菜', '日韩料理', '海鲜'],
      fxmeiweiList: ['老字号', '上榜好店', '清淡口味', '麻辣口味'],
      tagCategoryList: [],
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      }
    }
  },
  computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    }
  },
  created() {
    this.getList()
    this.getTagCategoryList()
  },
  methods: {
    getSortTime(date) {
      this.dataForm.sortTime = date
    },
    uploadBackPicUrl: function(response) {
      this.dataForm.backPicUrl = response.data.url
    },
    uploadPicUrl: function(response) {
      this.dataForm.picUrl = response.data.url
    },
    getList() {
      this.listLoading = true
      listStore(this.listQuery)
        .then(response => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    getTagCategoryList() {
      this.listLoading = true
      listTagCategoryList(this.listQuery)
        .then(response => {
          this.tagCategoryList = response.data.data
        })
        .catch(() => {
          this.tagCategoryList = []
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        name: undefined,
        description: '',
        latLon: undefined,
        address: undefined,
        images: [],
        avgConsumer: undefined,
        businessHours: undefined,
        dingzuoPhone: undefined,
        jcCount: undefined,
        jcDay: undefined,
        jcBeginTime: undefined,
        jcEndTime: undefined,
        jcTimeInterval: undefined,
        jcPlace: undefined,
        tags: [],
        recommendIndex: 1,
        isRecommended: false,
        backPicUrl: '',
        sortTime: undefined
      }
      this.galleryFileList = []
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    uploadUrl: function(response) {
      this.dataForm.url = response.data.url
    },
    checkFileSize: function(file) {
      if (file.size > 1048576) {
        this.$message.error(file.name + '文件大于1024KB，请选择小于1024KB大小的图片')
        return false
      }
      return true
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createStore(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '创建成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleUpdate(row) {
      listTagsList(row.id)
        .then(response => {
          this.resetForm()
          this.dataForm = Object.assign({}, row, { tags: [] })
          this.dialogStatus = 'update'
          this.dialogFormVisible = true
          this.galleryFileList = []

          if (this.dataForm.images) {
            for (var i = 0; i < this.dataForm.images.length; i++) {
              this.galleryFileList.push({
                url: this.dataForm.images[i]
              })
            }
          }

          this.$nextTick(() => {
            this.dataForm.tags = response.data.data
            this.$refs['dataForm'].clearValidate()
          })
        })
        .catch(() => {
          this.dataForm.tags = []
        })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updateStore(this.dataForm)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.dataForm.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新商家成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleDelete(row) {
      deleteStore(row)
        .then(response => {
          this.$notify.success({
            title: '成功',
            message: '删除成功'
          })
          this.getList()
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: response.data.errmsg
          })
        })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          '名字',
          '经纬度',
          '地址',
          '人均消费',
          '营业时间',
          '订座电话',
          '就餐人数',
          '就餐日期(天内)',
          '就餐起始时间',
          '就餐结束时间',
          '就餐时间间隔',
          '大厅数量',
          '包间数量'
        ]
        const filterVal = [
          'name',
          'latLon',
          'address',
          'avgConsumer',
          'businessHours',
          'dingzuoPhone',
          'jcCount',
          'jcDay',
          'jcBeginTime',
          'jcEndTime',
          'jcTimeInterval',
          'jcPlaceHall',
          'jcPlaceBigBag'
        ]
        excel.export_json_to_excel2(tHeader, this.list, filterVal, '商家信息')
        this.downloadLoading = false
      })
    },
    uploadOverrun: function() {
      this.$message({
        type: 'error',
        message: '上传文件个数超出限制!最多上传5张图片!'
      })
    },
    handleGalleryUrl(response, file, fileList) {
      if (response.errno === 0) {
        if (this.dataForm.images) {
          this.dataForm.images.push(response.data.url)
        }
      }
    },
    handleRemove: function(file, fileList) {
      for (var i = 0; i < this.dataForm.images.length; i++) {
        // 这里存在两种情况
        // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
        //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
        // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
        var url
        if (file.response === undefined) {
          url = file.url
        } else {
          url = file.response.data.url
        }

        if (this.dataForm.images[i] === url) {
          this.dataForm.images.splice(i, 1)
        }
      }
    }
  }
}
</script>
